# coding:utf-8

import urllib.request
from urllib.parse import quote
import time

citys = ['北京', '天津', '石家庄', '太原', '西安', '重庆', '成都', '贵阳', '上海', '苏州', '杭州', '南京', '广州',
         '深圳', '厦门', '武汉']

current_time = time.strftime('%Y-%m-%d')

for city in citys:
    try:
        # 对城市名进行URL编码
        encoded_city = quote(city)

        # 使用编码后的城市名构建URL
        url_aqi = f'http://www.baidu.com/s?ie=utf-8&bs={encoded_city}aqi&f=8&rsv_bp=1&rsv_spt=3&wd={encoded_city}aqi&inputT=0'
        url_tem = f'http://www.baidu.com/s?ie=utf-8&bs={encoded_city}气温&f=8&rsv_bp=1&rsv_spt=3&wd={encoded_city}气温&inputT=0'

        # 设置请求头，模拟浏览器访问
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

        # 创建请求对象
        req_aqi = urllib.request.Request(url=url_aqi, headers=headers)
        req_tem = urllib.request.Request(url=url_tem, headers=headers)

        # 发送请求并获取内容
        content_aqi = urllib.request.urlopen(req_aqi).read().decode('utf-8')
        content_tem = urllib.request.urlopen(req_tem).read().decode('utf-8')

        # 查找空气质量指数
        index_aqi_1 = content_aqi.find('class="op_pm25_graexp">')
        index_aqi_2 = content_aqi.find('</span><span class="op_pm25_grade')

        # 查找温度
        index_tem_1 = content_tem.find('twoicon_temp">')
        index_tem_2 = content_tem.find('<sup>℃</sup>')

        # 提取并打印结果
        if index_aqi_1 != -1 and index_aqi_2 != -1 and index_tem_1 != -1 and index_tem_2 != -1:
            aqi = content_aqi[index_aqi_1 + 23:index_aqi_2]
            temperature = content_tem[index_tem_1 + 14:index_tem_2]
            print(f"{city}: 空气质量指数：{aqi}    温度：{temperature}     时间：{current_time}")
        else:
            print(f"{city}: 未能获取到数据，请检查网页结构是否已变化")

    except urllib.error.HTTPError as e:
        print(f"{city}: HTTP错误 - {e.code}")
    except urllib.error.URLError as e:
        print(f"{city}: URL错误 - {e.reason}")
    except UnicodeEncodeError:
        print(f"{city}: 编码错误 - 请确保Python环境支持UTF-8")
    except Exception as e:
        print(f"{city}: 未知错误 - {str(e)}")

    # 添加延迟避免请求过于频繁
    time.sleep(1)